<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Dart入门笔记》 - Lucklyの博客 - 在阅读中遇见自己</title><meta name="Description" content="早起的年轻人做的网站"><meta property="og:title" content="《Dart入门笔记》" />
<meta property="og:description" content="
本文主要介绍Dart 基础知识笔记。
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://luckly.work/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/" />
<meta property="og:image" content="https://luckly.work/logo.png"/>
<meta property="article:published_time" content="2021-07-31T20:51:30+08:00" />
<meta property="article:modified_time" content="2021-07-31T20:51:30+08:00" />
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://luckly.work/logo.png"/>

<meta name="twitter:title" content="《Dart入门笔记》"/>
<meta name="twitter:description" content="
本文主要介绍Dart 基础知识笔记。
"/>
<meta name="application-name" content="LoveIt">
<meta name="apple-mobile-web-app-title" content="LoveIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://luckly.work/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/" /><link rel="prev" href="https://luckly.work/flutter-sample%E8%A7%A3%E6%9E%90/" /><link rel="next" href="https://luckly.work/dart%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E4%B9%8Bisolate%E5%92%8C%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF/" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13.0/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Dart入门笔记》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/luckly.work\/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0\/"
        },"image": [{
                            "@type": "ImageObject",
                            "url": "https:\/\/luckly.work\/images\/Apple-Devices-Preview.png",
                            "width":  3200 ,
                            "height":  2048 
                        }],"genre": "posts","keywords": "dart","wordcount":  2261 ,
        "url": "https:\/\/luckly.work\/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0\/","datePublished": "2021-07-31T20:51:30+08:00","dateModified": "2021-07-31T20:51:30+08:00","license": "This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.","publisher": {
            "@type": "Organization",
            "name": "xxxx","logo": {
                    "@type": "ImageObject",
                    "url": "https:\/\/luckly.work\/images\/avatar.png",
                    "width":  528 ,
                    "height":  560 
                }},"author": {
                "@type": "Person",
                "name": "早起的年轻人"
            },"description": ""
    }
    </script></head>
    <body header-desktop="fixed" header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">Lucklyの博客 - 在阅读中遇见自己</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/posts/">所有文章</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/flutter/">Flutter</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/read/">读书笔记</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/go/">Go</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/tags/">标签</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/">分类</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="https://github.com/ITmxs">Github</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/friend/">友链</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Dart入门笔记》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>早起的年轻人</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/dart/"><i class="far fa-folder fa-fw"></i>dart</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-31">2021-07-31</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 2261 字&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 5 分钟&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#tour">tour</a></li>
    <li><a href="#断言">断言</a></li>
    <li><a href="#构造函数">构造函数</a></li>
    <li><a href="#隐式接口">隐式接口</a></li>
    <li><a href="#mixin">Mixin</a></li>
    <li><a href="#语法糖">语法糖</a></li>
    <li><a href="#其他内容">其他内容</a></li>
    <li><a href="#参考">参考</a></li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍Dart 基础知识笔记。</p>
</blockquote>
<h1 id="tour">tour</h1>
<ul>
<li><code>main()</code> 函数是 Dart 程序的入口</li>
<li><code>main()</code> 函数返回 <code>void</code> 并具有可选的 <code>List&lt;String&gt;</code> 参数作为参数</li>
<li>所有对象都从 <code>Object</code> 类继承</li>
<li>Dart 是强类型</li>
<li>当您想明确地不希望有任何类型时，使用特殊类型 <code>dynamic</code></li>
<li>Dart 可以在函数内创建函数（ 嵌套 函数或局部函数 ），可以创建匿名函数</li>
<li>Dart 支持顶级变量</li>
<li>标识符以下划线（_）开头时表示私有成员变量</li>
<li>Dart 支持类型推断，<code>var name = 'Bob';</code> 这里的 name 类型推断为 String</li>
<li>未初始化的变量的初始值为 <code>null</code>，包括数字类型</li>
<li>Dart 字符串是 UTF-16 代码单元(code unit)的序列，在字符串中表示32位 Unicode 值时需要特殊语法 <code>Runes</code></li>
<li>在字符串前添加 r 来创建”原始”字符串，<code>var s = r'In a raw string</code></li>
<li>在Dart中，数组是 <code>List</code> 对象</li>
<li>Dart 支持集合字面量，<code>var halogens = {'fluorine', 'chlorine'}</code></li>
<li><code>{}</code> 默认为 Map 类型，<code>var names = {};</code> 创建了 <code>Map</code> 而不是 <code>Set</code></li>
<li>Dart <code>new</code> 关键字是可选的 (Dart 2开始)</li>
<li>Dart 中函数也是对象，其类型为 <code>Function</code>，可以将函数分配给变量或作为参数传递给其他函数</li>
<li>Dart 中的箭头语法 <code>=&gt; expr</code> 用于简化仅包含一个表达式的函数</li>
<li>Dart 函数可以具有两种类型的参数： required和optional . 首先列出必需的参数，然后列出所有可选参数</li>
<li>Dart 函数的可选参数可以是命名参数，也可以是位置参数</li>
<li>Dart 函数可以使用 <code>=</code> 来定义命名参数和位置参数的默认值。默认值必须是编译时常量</li>
<li><code>~/</code> 返回除法的整数结果</li>
<li>Dart 中的 <code>switch</code> 语句使用 <code>==</code> 比较整数、字符串、枚举或编译时常量</li>
<li>Dart的所有异常都是未经检查的异常</li>
<li>Dart 提供 <code>Exception</code> 和 <code>Error</code> 类型，并且支持将任何非 <code>null</code> 对象作为异常抛出</li>
<li>某些语言（例如Java）将文件的组织与类的组织联系在一起-每个文件只能定义一个顶级类. Dart没有此限制</li>
<li>Dart 是一种具有类和基于 Mixin 的继承的面向对象语言</li>
<li>Object 的 <code>runtimeType</code> 属性返回对象类型</li>
<li>所有实例变量都会生成一个隐式的 getter 方法. 非 final 的实例变量还会生成隐式的 setter 方法</li>
<li>Dart 中每个类都隐式定义一个接口</li>
<li>Dart 泛型在运行时会携带其类型信息 (相反，Java中 的泛型使用了 erasure ，这意味着在运行时会删除泛型类型参数. 在 Java 中，您可以测试对象是否为 List，但不能测试对象是否为 List )</li>
<li>Dart 使用 async 和 await 关键字支持异步编程，使您可以编写看起来类似于同步代码的异步代码</li>
<li>可以使用 Future API 或 <code>async/await</code> 关键字处理 Future 结果</li>
<li>可以使用 Stream API 或 <code>await for</code> 处理 Stream 结果</li>
<li>仅 dart2js 支持延迟加载库. Flutter，Dart VM和dartdevc不支持延迟加载</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">// 延迟导入库
import &#39;package:greetings/hello.dart&#39; deferred as hello;

// 使用库
Future greet() async {
  await hello.loadLibrary();
  hello.printGreeting();
}
</code></pre></td></tr></table>
</div>
</div><h1 id="断言">断言</h1>
<p>开发过程中可以使用 <code>assert(condition , optionalMessage)</code> 断言，检查某些条件是否为真。断言通常由工具或框架决定是否生效：</p>
<ul>
<li>Flutter 在 debug 模式下启用断言</li>
<li>默认情况下，仅开发工具（例如 <a href="http://s0dart0dev.icopy.site/tools/dartdevc" target="_blank" rel="noopener noreffer">dartdevc</a>）启用断言</li>
<li>某些工具，比如 <a href="http://s0dart0dev.icopy.site/server/tools/dart-vm" target="_blank" rel="noopener noreffer">dart</a> 通过 <code>--enable-asserts</code> 标志启用断言</li>
</ul>
<h1 id="构造函数">构造函数</h1>
<p>Dart 中的构造函数跟 Java 中的构造函数还是有不小的区别，所以值得独立作为一节来讨论。</p>
<p>这里先列出了 Dart 构造函数相关的一些术语。</p>
<ul>
<li>Default constructors</li>
<li>Named constructors</li>
<li>Initializer list</li>
<li>Redirecting constructors</li>
<li>Constant constructors</li>
<li>Factory constructors</li>
</ul>
<p>如果你清楚这些术语，说明你已经基本掌握了 Dart 构造函数，完全可以略过本节。如果不清楚，不妨往下看。</p>
<p>Dart 中通过创建一个与其类具有相同名称的函数来声明一个构造函数。可以很方便地将构造函数参数赋值给实例变量：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">class Point {
  num x, y;

  // Syntactic sugar for setting x and y
  // before the constructor body runs.
  Point(this.x, this.y);
}
</code></pre></td></tr></table>
</div>
</div><p>Dart 中使用命名构造函数可为一个类实现多个构造函数或提供额外的清晰度：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">class Point {
  num x, y;

  Point(this.x, this.y);

  // Named constructor
  Point.origin() {
    x = 0;
    y = 0;
  }
}
</code></pre></td></tr></table>
</div>
</div><p>构建函数的执行顺序如下：</p>
<ul>
<li>初始化列表</li>
<li>超类的无参数构造函数</li>
<li>主类的无参数构造函数</li>
</ul>
<p>注意：如果超类没有未命名，无参数的构造函数，则必须手动调用超类中的构造函数之一</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">class Employee extends Person {
  Employee() : super.fromJson(getDefaultData());
  // ···
}
</code></pre></td></tr></table>
</div>
</div><p>在实现并非总是创建其类的新实例的构造函数时，要使用 <code>factory</code> 关键字。示例如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">class Logger {
  final String name;
  bool mute = false;

  // _cache is library-private, thanks to
  // the _ in front of its name.
  static final Map&lt;String, Logger&gt; _cache =
      &lt;String, Logger&gt;{};

  factory Logger(String name) {
    return _cache.putIfAbsent(
        name, () =&gt; Logger._internal(name));
  }

  Logger._internal(this.name);

  void log(String msg) {
    if (!mute) print(msg);
  }
}
</code></pre></td></tr></table>
</div>
</div><h1 id="隐式接口">隐式接口</h1>
<p>每个类都隐式定义一个接口。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">// A person. The implicit interface contains greet().
class Person {
  // In the interface, but visible only in this library.
  final _name;

  // Not in the interface, since this is a constructor.
  Person(this._name);

  // In the interface.
  String greet(String who) =&gt; &#39;Hello, $who. I am $_name.&#39;;
}

// An implementation of the Person interface.
class Impostor implements Person {
  get _name =&gt; &#39;&#39;;

  String greet(String who) =&gt; &#39;Hi $who. Do you know who I am?&#39;;
}
</code></pre></td></tr></table>
</div>
</div><h1 id="mixin">Mixin</h1>
<p>Mixins是在多个类层次结构中重用类代码的一种方式。</p>
<p>首先看如何实现 mixin。使用 <code>mixin</code> 关键字创建一个扩展自 Object 且不声明构造函数的类。还可以使用 <code>on</code> 关键字来限定可以使用该 mixin 的类</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">mixin Musical {
  bool canPlayPiano = false;
  bool canCompose = false;
  bool canConduct = false;

  void entertainMe() {
    if (canPlayPiano) {
      print(&#39;Playing piano&#39;);
    } else if (canConduct) {
      print(&#39;Waving hands&#39;);
    } else {
      print(&#39;Humming to self&#39;);
    }
  }
}

mixin MusicalPerformer on Musician {
  // ···
}
</code></pre></td></tr></table>
</div>
</div><p>再来看如何使用 mixin</p>
<h1 id="语法糖">语法糖</h1>
<p>从设计者角度来说是一些锦上添花的语言特性，但从开发者角度来确实很方便。</p>
<p>类型推断</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">num highScore(List&lt;num&gt; scores) {
  var highest = 0;
  for (var score in scores) {
    if (score &gt; highest) highest = score;
  }
  return highest;
}
</code></pre></td></tr></table>
</div>
</div><p>扩展操作符 <code>...</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);
</code></pre></td></tr></table>
</div>
</div><p>nullable 扩展操作符 <code>...?</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">var list;
var list2 = [0, ...?list];
assert(list2.length == 1);
</code></pre></td></tr></table>
</div>
</div><p>命名参数 (Named parameters) <code>paramName : value</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">// 定义命名参数
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold, bool hidden}) {...}

// 指定命名参数
enableFlags(bold: true, hidden: false);
</code></pre></td></tr></table>
</div>
</div><p>位置参数 (Positional parameters)</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">// 使用[]标记一组可选的位置参数
String say(String from, String msg, [String device]) {
  ...
}
</code></pre></td></tr></table>
</div>
</div><p>级联操作符 <code>..</code>。这个操作符可以节省创建临时变量的步骤。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">void main() {
  querySelector(&#39;#sample_text_id&#39;)
    ..text = &#39;Click me!&#39;
    ..onClick.listen(reverseText);
}
</code></pre></td></tr></table>
</div>
</div><p>匿名函数</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">var list = [&#39;apples&#39;, &#39;bananas&#39;, &#39;oranges&#39;];
list.forEach((item) {
  print(&#39;${list.indexOf(item)}: $item&#39;);
});
</code></pre></td></tr></table>
</div>
</div><p><code>??=</code> 操作符。这个操作符让代码更简洁</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">// Assign value to b if b is null; otherwise, b stays the same
b ??= value;
</code></pre></td></tr></table>
</div>
</div><p><code>??</code> 操作符。这个操作符让代码更简洁</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">// 如果 name 为 null 则返回 &#39;Guest&#39;
String playerName(String name) =&gt; name ?? &#39;Guest&#39;;
</code></pre></td></tr></table>
</div>
</div><p><code>?.</code> 操作符，表示有条件的成员访问，最左边的操作数可以为 null</p>
<p>typedef 用于给函数类型提供一个名称</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">typedef Compare = int Function(Object a, Object b);

class SortedCollection {
  Compare compare;

  SortedCollection(this.compare);
}

// Initial, broken implementation.
int sort(Object a, Object b) =&gt; 0;

void main() {
  SortedCollection coll = SortedCollection(sort);
  assert(coll.compare is Function);
  assert(coll.compare is Compare);
}
</code></pre></td></tr></table>
</div>
</div><h1 id="其他内容">其他内容</h1>
<ul>
<li>使用 <code>operator</code> 来重载操作符</li>
<li>noSuchMethod</li>
<li>callable class。对于实现了 <code>call()</code> 方法的类，可以像调用函数一样调用该类的实例</li>
</ul>
<h1 id="参考">参考</h1>
<p><a href="https://renato.athaydes.com/posts/interesting-dart-features.html#quick-dart-overview">https://renato.athaydes.com/posts/interesting-dart-features.html#quick-dart-overview</a></p></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2021-07-31</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://luckly.work/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/" data-title="《Dart入门笔记》" data-hashtags="dart"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://luckly.work/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/" data-hashtag="dart"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Hacker News" data-sharer="hackernews" data-url="https://luckly.work/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/" data-title="《Dart入门笔记》"><i class="fab fa-hacker-news fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://luckly.work/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/" data-title="《Dart入门笔记》"><i data-svg-src="https://cdn.jsdelivr.net/npm/simple-icons@2.14.0/icons/line.svg"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://luckly.work/dart%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/" data-title="《Dart入门笔记》" data-image="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"><i class="fab fa-weibo fa-fw"></i></a></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/dart/">dart</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/flutter-sample%E8%A7%A3%E6%9E%90/" class="prev" rel="prev" title="《Flutter  Sample解析》"><i class="fas fa-angle-left fa-fw"></i>《Flutter  Sample解析》</a>
            <a href="/dart%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E4%B9%8Bisolate%E5%92%8C%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF/" class="next" rel="next" title="《Dart异步编程之Isolate和事件循环》">《Dart异步编程之Isolate和事件循环》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">早起的年轻人</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.css"><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.37.1/dist/autocomplete.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/algoliasearch@4.2.0/dist/algoliasearch-lite.umd.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lazysizes@5.2.2/lazysizes.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":10},"comment":{},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验."},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"search":{"algoliaAppID":"PASDMWALPK","algoliaIndex":"index.zh-cn","algoliaSearchKey":"b42948e51daaa93df92381c8e2ac0f93","highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50,"type":"algolia"}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
